import 'dart:convert';

import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:yysk_app/net/api/pay_url.dart';
import 'package:yysk_app/net/http.dart';
import 'package:yysk_app/pages/nft_pages/pay_pages/confirm_payment/confirm_payment_controller.dart';
import 'package:yysk_app/pages/nft_pages/wallet_pages/manage_bank/manage_bank_controller.dart';
import 'package:oktoast/oktoast.dart';
// AddBankCardController
class AddBankCardController extends GetxController {
  var nameController = TextEditingController();
  var idController = TextEditingController();
  var cardNoController = TextEditingController();
  var phoneController = TextEditingController();
  var smsController = TextEditingController();
  var agree = true.obs;
  var isLoading = false.obs;
  var smsBtnText = '获取验证码'.obs;
  var titleText = '添加结算卡'.obs;
  Timer? _timer;
  Timer? timer2;
  int _seconds = 0;
  var bindType = 'WITHDRAW'.obs;
  var id = 0.obs;
  var isBind = false.obs;
  var comeFrom = 'add'.obs;  //add 添加 ，Withdrawal 提现 ，order 订单

  var isLong = false.obs;
  var certValidityType = 0.obs;
  var bankName = ''.obs;
  var bankCode = ''.obs;
  var branchName = ''.obs;
  var branchCode = ''.obs;
  var certBeginDate = ''.obs;
  var certEndDate = ''.obs;
    var province = ''.obs;
     var provinceId = ''.obs;
     var city = ''.obs;
     var cityId = ''.obs;
     var plat = 'USER'.obs;
  var citys = RxList<dynamic?>([]);
  @override
  void onInit() {
    super.onInit();
    getAutherInfo();
      _loadCitys();
      comeFrom.value = Get.parameters['comeFrom'] ?? Get.arguments['comeFrom'];
      titleText.value = Get.arguments['titleText'] ??'添加结算卡';
      plat.value = Get.arguments['plat']??'USER';
  }
  // 加载省市区数据
  Future<void> _loadCitys() async {
    try {
      final data = await rootBundle.loadString('static/json/city_list.json');
      final jsonData = json.decode(data);
      citys.value = jsonData;
    } catch (e) {
      print("加载省市区数据失败: $e");
    }
  }

  @override
  void onClose() {
    nameController.dispose();
    idController.dispose();
    cardNoController.dispose();
    phoneController.dispose();
    smsController.dispose();
    _timer?.cancel();
    timer2?.cancel();
    super.onClose();
  }

  // void pickCardNoFromImage() async {
  //   // TODO: 调用银行卡号识别接口
  //   final picker = ImagePicker();
  //   final picked = await picker.pickImage(source: ImageSource.gallery);
  //   if (picked != null) {
  //     // 假设识别到卡号 6222 8888 8888 8888
  //     cardNoController.text = '6222888888888888';
  //   }
  // }

  void getSmsCode() {
    if (_seconds > 0) return;
    // TODO: 请求服务器发送验证码
    _seconds = 60;
    smsBtnText.value = '60s';
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      _seconds--;
      if (_seconds <= 0) {
        timer.cancel();
        smsBtnText.value = '获取验证码';
      } else {
        smsBtnText.value = '${_seconds}s';
      }
    });
  }

  Future getbankCardId() async {
    final RegExp phoneRegExp = RegExp(r'^1[3-9]\d{9}$');
    if (!phoneRegExp.hasMatch(phoneController.text)) {
      showToast('请输入正确的手机号码格式');
      return ;
    }
     if(certBeginDate.value==''||certEndDate.value==''){
       showToast('请选择证件有效期');
      return;
    }
    await http.netFetch<dynamic>(
      PayUrl.bankCardBind,
      method: Method.post,
      params: {
        'channel': 'HUIFU',
        'bindType': bindType.value,
        "cardNo": cardNoController.text,
        "mobile": phoneController.text,
        "plat":plat.value,
        "certValidityType":isLong.value==false?'0':'1',
        'certBeginDate':certBeginDate.value,
        'certEndDate':certEndDate.value,
        'bankName':bankName.value,
        "bankCode":bankCode.value,
        'branchName':branchName.value,
        'branchCode':branchCode.value,
        'provinceId':provinceId.value,
        'cityId':cityId.value
      },
      success: (res) {
        if(res.code==200){
          if(comeFrom.value=='add'){  //来自添加添加银行卡
 
            try{
            ManageBankController manageBankController = Get.find();
          manageBankController.getBankList();
           showToast('绑定成功');
          Get.back();
          }catch(e){
             showToast('绑定成功');
             Get.back();
          }
        }
        
       }
   
      },
    );
  }

Future submit() async {
  await http.netFetch<dynamic>(
      PayUrl.confirmBind,
      method: Method.post,
      params: {
        'id': id.value,
         "smsCode": smsController.text
       
      },
      success: (res) {
       if(res.code==200){
          if(comeFrom.value=='add'){  //来自添加添加银行卡
          try{
            ManageBankController manageBankController = Get.find();
          manageBankController.getBankList();
          Get.back();
          }catch(e){
             Get.back();
          }
        }else if(comeFrom.value=='mallAdd'){
          ConfirmPaymentController confirmPaymentController = Get.find();
          confirmPaymentController.getBankList("HUIFU");
          Get.back();
        }
       }
      }
    );
  }
// Future isBindCard() async {
    
//     await http.netFetch<dynamic>(
//       PayUrl.isBind,
//       method: Method.post,
//       params: {
//         'channel': 'HUIFU',
//          "cardNo": cardNoController.text
//       },
//       success: (res) {
//        if(res.code==200){
//         isBind.value = res.data??false;
//        }
//       },
//     );
//   }
 // 实名信息查询

  Future<void> getAutherInfo() async {
    http.netFetch<dynamic>(
      PayUrl.realNameQuery,
      method: Method.post,
   
      success: (r) {
      nameController.text= r.data['realName'];
      idController.text= r.data['idNo'];
        return r;
      },
    );
  }
   void pickValidityDate(int type) async {
    DateTime? picked = await showDatePicker(
      context: Get.context!,
      initialDate: DateTime.now(),
      firstDate: DateTime(1900),
      lastDate: DateTime(2100),
      initialEntryMode: DatePickerEntryMode.input
    );
    if (picked != null) {
      if(type==0){
        certBeginDate.value = '${picked.year}${picked.month>10?picked.month:"0${picked.month}"}${picked.day>10?picked.day:"0${picked.day}"}';
      }else{
        certEndDate.value = '${picked.year}${picked.month>10?picked.month:"0${picked.month}"}${picked.day>10?picked.day:"0${picked.day}"}';
      }
     
    }
  }
  
}
